#!/bin/bash

backup_dir=${BACKUP_DIR:-"/tmp/backups"}
db_name=${DB_NAME:-"cics"}
db_user=${DB_USER:-"cics"}
db_pass=${DB_PASS:-"cics"}
db_host=${DB_HOST:-"172.31.18.111"}
db_port=${DB_PORT:-"3306"}
log_eanble=${LOG_ENABLE:-1}
log_dir=${LOG_DIR:-"/tmp/logs"}
mysql_80=${MYSQL_80:-0}
sequence=$(date "+%Y-%m-%d-%H")
script_name=$(basename $0)
log_file="${log_dir}/log_${script_name}_${sequence}.log"


[[ -d ${backup_dir} ]] || mkdir -p $backup_dir
[[ -d ${log_dir} ]] || mkdir -p $log_dir
[[ -f "./env" ]] && . ./env

function output() {
    local msg=$*
    if [[ "x${log_eanble}" == "x1" ]]
    then
        echo $msg | tee -a ${log_file} >/dev/null
    else
        echo $msg
    fi
}


function check_return() {
    # $1 == $?
    local ret_code=$1
    local expected_val=$2
    local msg=$3
    if [[ "x$ret_code" == "x" ]] || [[ "x$expected_val" == "x" ]] || [[ "x$msg" == "x" ]]
    then
        output "Parameter error"
        exit 1
    fi
    if [[ "x$ret_code" != "x$expected_val" ]]
    then
        output $msg
        exit $ret_code
    fi
}

function start_backup() {
    output "Start backup @${sequence}"
    cd $backup_dir
    if [[ "x${mysql_80}" == "x0" ]]
    then
        # 8.0以下
        mysqldump -h $db_host -P $db_port -u$db_user -p$db_pass --set-gtid-purged=OFF --no-tablespaces --databases $db_name > ${db_name}_${sequence}.sql 2>> ${log_file}
    else
        # 8.0以上
        mysqldump -h $db_host -P $db_port -u$db_user -p$db_pass --set-gtid-purged=OFF --no-tablespaces --column-statistics=0 --databases $db_name > ${db_name}_${sequence}.sql 2>> ${log_file}
    fi
    check_return $? 0 "Dump sql failed"
    tar -zcf ${db_name}_${sequence}.sql.tgz ${db_name}_${sequence}.sql
    check_return $? 0 "Tar sql failed"
    rm ${db_name}_${sequence}.sql
    cd - >/dev/null
    output "End backup"
}

function cleanup_backups() {
    output "Clean up backups(do nothing)"
    # output "/data usage"
    # local stats_total=$(df -h /data | grep /data | awk '{print $2}')
    # local stats_used=$(df -h /data | grep /data | awk '{print $3}')
    # local stats_free=$(df -h /data | grep /data | awk '{print $4}')
    # local stats_usage=$(df -h /data | grep /data | awk '{print $5}')
    # output "Total: ${stats_total}, Used: ${stats_used}, Free: ${stats_free}, Usage: ${stats_usage}"
    # output "Count of backup file"
    # local stats_count=$(ls $backup_dir/*.tgz 2>/dev/null | wc -l)
    # output $stats_count
    output "End Clean up"
    output ""
}

function check_system_require() {
    output "System check"
}


function main() {
    check_system_require
    start_backup
    cleanup_backups
}

main


